package com.starhub.application.rag.config;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import jakarta.annotation.PreDestroy;
import lombok.extern.slf4j.Slf4j;

import org.springframework.stereotype.Component;

/**
 * 公共线程池配置类
 * 提供RAG服务中使用的线程池实例
 * 
 * @version: V1.0
 * @author: liuhf
 * @time 2025-01-27
 */
@Slf4j
@Component
public class ThreadPoolConfig {

    // 线程池定义
    private final ExecutorService threadPoolExecutor = new ThreadPoolExecutor(
            2, // 核心线程数
            10, // 最大线程数
            60L, // 空闲线程存活时间
            TimeUnit.SECONDS, // 时间单位
            new LinkedBlockingQueue<>(100), // 工作队列，容量100
            new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略：调用者运行
    );

    /**
     * 获取线程池实例
     * 
     * @return 线程池实例
     */
    public ExecutorService getThreadPoolExecutor() {
        return threadPoolExecutor;
    }

    /**
     * 应用关闭时清理线程池
     */
    @PreDestroy
    public void cleanup() {
        log.info("Shutting down thread pool executor...");
        threadPoolExecutor.shutdown();
        try {
            if (!threadPoolExecutor.awaitTermination(60, TimeUnit.SECONDS)) {
                threadPoolExecutor.shutdownNow();
            }
        } catch (InterruptedException e) {
            threadPoolExecutor.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
} 